package com.wzw.springboot.principle.use.security.infrastructure.provider;

import com.wzw.springboot.principle.use.security.enums.AuthenticationEnum;
import com.wzw.springboot.principle.use.security.manage.RbacManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 1.判断是否支持
 * 2.获取UserDetails
 * 3.检查用户状态
 * 4.检查用户凭证
 * 5.构建认证成功的对象
 *
 * @author Wangzhiwen
 */
public class SmsCodeAuthenticationProvider extends AbstractGeneralAuthenticationProvider<SmsCodeAuthenticationToken> {

    private final RbacManager rbacManager;

    public SmsCodeAuthenticationProvider(RbacManager rbacManager) {
        this.rbacManager = rbacManager;
    }

    @Override
    protected AuthenticationEnum getEnum() {
        return AuthenticationEnum.MOBILE;
    }

    // 返回认证成功的对象
    @Override
    protected Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) {
        SmsCodeAuthenticationToken smsCodeAuthenticationToken = new SmsCodeAuthenticationToken(user, authentication.getCredentials(), user.getAuthorities());
        smsCodeAuthenticationToken.setDetails(authentication.getDetails());
        return smsCodeAuthenticationToken;
    }

    // 获取UserDetails
    @Override
    protected UserDetails retrieveUser(String mobile, SmsCodeAuthenticationToken authentication) throws AuthenticationException {
        return rbacManager.getSecurityUserByMobile(mobile);
    }

    // 是否支持
    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
